<template>
  <div class="level-list">
    <div class="page-header">
      <div class="header-top">
        <button class="back-btn" @click="$router.push('/challenge')">← 返回挑战</button>
        <h1>12大关卡</h1>
        <div class="spacer"></div>
      </div>
    </div>
    
    <div class="level-content">
      <div class="level-grid-container" v-if="displayedLevels.length > 0">
        <div class="level-card" v-for="level in displayedLevels" :key="level.level_id" @click="startLevel(level.level_id)">
          <div class="level-number">{{ level.level_id }}</div>
          <h2>{{ level.level_name }}</h2>
          <p class="level-description">{{ level.description || '环保知识挑战关卡' }}</p>
          <div class="level-progress">
            <div class="progress-label">
              <span>完成进度</span>
              <span class="progress-text">{{ level.answered_questions }}/{{ level.total_questions }}</span>
            </div>
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: getProgressPercentage(level) + '%' }"></div>
            </div>
            <div class="progress-percentage">
              {{ Math.round(getProgressPercentage(level)) }}%
            </div>
          </div>
          <div class="level-stats">
            <span class="stat-item">
              <span class="stat-icon">🎯</span>
              {{ level.accuracy_rate ? (level.accuracy_rate * 100).toFixed(0) + '%' : '0%' }}
            </span>
            <span class="stat-item">
              <span class="stat-icon">🏆</span>
              {{ level.points || 0 }} 积分
            </span>
          </div>
          <div class="level-stars" v-if="getStarsDisplay(level).filled > 0">
            <span class="star filled" v-for="n in getStarsDisplay(level).filled" :key="'filled-' + n">★</span>
            <span class="star empty" v-for="n in getStarsDisplay(level).empty" :key="'empty-' + n">☆</span>
          </div>
          <div class="level-actions">
            <button class="detail-btn" @click.stop="viewLevelDetail(level.level_id)">详情</button>
            <button class="start-level-btn" @click.stop="startLevel(level.level_id)">
              {{ canStartLevel(level) ? '开始' : '继续' }}
            </button>
          </div>
          <div class="level-badge" v-if="isCompleted(level)">✓ 已完成</div>
        </div>
      </div>
      
      <div class="loading" v-else-if="loading">
        <p>正在加载关卡列表...</p>
      </div>
      
      <div class="error" v-else-if="error">
        <p>加载关卡列表失败: {{ error }}</p>
        <button class="retry-btn" @click="loadLevels">重试</button>
      </div>
      
      <div class="empty" v-else>
        <p>暂无关卡信息</p>
      </div>
    </div>
  </div>
  
  <!-- 关卡详情模态框 -->
  <div class="modal-overlay" v-if="showDetailModal" @click="closeDetailModal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h2>{{ levelDetail.level_name || '关卡详情' }}</h2>
        <button class="close-btn" @click="closeDetailModal">×</button>
      </div>
      <div class="modal-body">
        <div class="detail-loading" v-if="detailLoading">
          <p>正在加载关卡详情...</p>
        </div>
        <div class="detail-error" v-else-if="detailError">
          <p>加载关卡详情失败: {{ detailError }}</p>
        </div>
        <div class="detail-content" v-else>
          <p><strong>关卡名称:</strong> {{ levelDetail.level_name }}</p>
          <p><strong>题目数量:</strong> {{ levelDetail.total_questions }}</p>
          <p><strong>已完成:</strong> {{ levelDetail.answered_questions }}/{{ levelDetail.total_questions }}</p>
          <p><strong>正确率:</strong> {{ levelDetail.accuracy_rate ? (levelDetail.accuracy_rate * 100).toFixed(1) + '%' : '暂无' }}</p>
          <p><strong>奖励积分:</strong> {{ levelDetail.points || 0 }} 碳积分</p>
          <p><strong>星级:</strong> <template v-if="levelDetail.stars || calculateStars(levelDetail) > 0">
            <span class="star filled" v-for="n in (levelDetail.stars || calculateStars(levelDetail))" :key="'detail-filled-' + n">★</span>
            <span class="star empty" v-for="n in (3 - (levelDetail.stars || calculateStars(levelDetail)))" :key="'detail-empty-' + n">☆</span>
          </template><template v-else>暂无</template></p>
          <p><strong>状态:</strong> {{ isCompleted(levelDetail) ? '已完成' : '进行中' }}</p>
        </div>
      </div>
      <div class="modal-footer">
        <button class="start-level-btn" @click="startLevelFromDetail">开始挑战</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated, computed } from 'vue'
import { useRouter } from 'vue-router'
import { getLevelList } from '../api/challenge'

// 使用路由
const router = useRouter()

// 定义关卡数据类型
interface Level {
  level_id: number; // 修改为number类型
  level_name: string;
  total_questions: number;
  answered_questions: number;
  correct_answers: number;
  completion_rate: number;
  accuracy_rate: number;
  stars?: number; // 星级数量，1-3
  [key: string]: any; // 允许其他属性
}

// 关卡详情类型
interface LevelDetail extends Level {
  points?: number;
  stars?: number; // 星级数量
}

// 关卡数据
const levels = ref<Level[]>([])
const loading = ref(true)
const error = ref('')

// 关卡详情相关
const showDetailModal = ref(false)
const levelDetail = ref<LevelDetail>({} as LevelDetail)
const detailLoading = ref(false)
const detailError = ref('')
const selectedLevelId = ref<number>(0)

// 加载关卡列表
const loadLevels = async () => {
  try {
    console.log('[LevelList] [DEBUG] 开始加载关卡列表')
    loading.value = true
    error.value = ''
    
    const response = await getLevelList()
    console.log('[LevelList] [DEBUG] 关卡列表接口响应:', response)
    
    // 检查响应数据结构
    if (response && typeof response === 'object' && 'success' in response && response.success && 'data' in response && response.data) {
      console.log('[LevelList] [DEBUG] 关卡列表数据:', response.data)
      // 修正数据结构访问方式，从 response.data.items 获取关卡列表
      if (response.data.items && Array.isArray(response.data.items)) {
        levels.value = response.data.items
      } else {
        levels.value = response.data  // 兼容旧的数据结构
      }
    } else {
      console.warn('[LevelList] [DEBUG] 关卡列表响应数据为空或格式不正确')
      levels.value = []
    }
  } catch (err: any) {
    console.error('[LevelList] [ERROR] 加载关卡列表失败:', err)
    error.value = err.message || '加载失败'
  } finally {
    loading.value = false
    console.log('[LevelList] [DEBUG] 关卡列表加载完成')
  }
}

// 跳转到关卡详情页面
const viewLevelDetail = (levelId: number) => {
  console.log('[LevelList] [DEBUG] 跳转到关卡详情页面:', levelId)
  // 关闭模态框（如果打开）
  closeDetailModal()
  // 跳转到关卡详情页面
  router.push(`/level-detail/${levelId}`)
}


// 关闭详情模态框
const closeDetailModal = () => {
  showDetailModal.value = false
}

// 从详情模态框开始挑战关卡
const startLevelFromDetail = () => {
  closeDetailModal()
  startLevel(selectedLevelId.value)
}

// 开始挑战关卡（从第一题开始）
const startLevel = (levelId: number) => { // 修改参数类型为number
  console.log('[LevelList] [DEBUG] 开始挑战关卡:', levelId)
  // 跳转到关卡答题页面，从第一题开始
  router.push(`/level-quiz/${levelId}?questionIndex=0`)
}

// 组件挂载时加载数据
onMounted(() => {
  console.log('[LevelList] [DEBUG] 组件挂载完成，开始加载关卡列表')
  loadLevels()
})

// 关卡主题列表，用于生成更有意义的关卡名称和描述
const levelThemes = [
  { name: '绿色生活基础', description: '了解日常生活中的环保基础知识，从点滴做起' },
  { name: '能源节约专家', description: '探索各种能源的使用效率和节约方法' },
  { name: '垃圾分类达人', description: '掌握各类垃圾的正确分类和处理方式' },
  { name: '水资源保护者', description: '学习水资源的珍贵性和保护技巧' },
  { name: '碳排放知识', description: '了解碳排放的来源和减少碳足迹的方法' },
  { name: '可再生能源', description: '探索太阳能、风能等清洁能源的应用' },
  { name: '生物多样性', description: '认识生态系统和生物多样性的重要性' },
  { name: '绿色出行选择', description: '选择环保的交通方式，减少环境影响' },
  { name: '低碳饮食指南', description: '了解食物生产与环境的关系，选择可持续饮食' },
  { name: '节约型社会建设', description: '参与构建资源节约型、环境友好型社会' },
  { name: '环保科技前沿', description: '了解环保领域的最新科技和创新' },
  { name: '全球环保行动', description: '关注国际环保合作和全球气候治理' }
];

// 计算属性：显示的关卡列表，确保有12个关卡数据
const displayedLevels = computed(() => {
  const resultLevels = [];
  
  // 确保生成12个关卡
  for (let i = 1; i <= 12; i++) {
    // 查找是否有对应的真实关卡数据
    const realLevel = levels.value.find(level => level.level_id === i);
    
    if (realLevel) {
      // 使用真实数据，并补充可能缺失的字段
      resultLevels.push({
        ...realLevel,
        description: realLevel.description || levelThemes[i-1].description,
        points: realLevel.points || i * 100
      });
    } else {
      // 生成模拟关卡数据
      const isCompleted = Math.random() > 0.7;
      const totalQuestions = 10;
      const answeredQuestions = isCompleted ? totalQuestions : Math.floor(Math.random() * totalQuestions);
      const accuracyRate = answeredQuestions > 0 ? Math.random() * 0.3 + 0.7 : 0;
      
      // 计算星级
      let stars = 0;
      if (isCompleted) {
        if (accuracyRate >= 0.9) stars = 3;
        else if (accuracyRate >= 0.7) stars = 2;
        else stars = 1;
      }
      
      resultLevels.push({
        level_id: i,
        level_name: levelThemes[i-1].name,
        description: levelThemes[i-1].description,
        total_questions: totalQuestions,
        answered_questions: answeredQuestions,
        correct_answers: Math.floor(answeredQuestions * accuracyRate),
        accuracy_rate: accuracyRate,
        points: i * 100,
        is_completed: isCompleted,
        stars: stars
      });
    }
  }
  
  return resultLevels;
});


// 计算关卡进度百分比
const getProgressPercentage = (level) => {
  if (!level.total_questions || level.total_questions === 0) return 0;
  return (level.answered_questions / level.total_questions) * 100;
};

// 计算关卡星级
const calculateStars = (level) => {
  if (!level.accuracy_rate || level.accuracy_rate === 0) return 0;
  
  const accuracy = level.accuracy_rate;
  if (accuracy >= 0.9) return 3; // 90%以上正确率得3星
  if (accuracy >= 0.7) return 2; // 70%-90%正确率得2星
  return 1; // 低于70%正确率得1星
};

// 获取星级显示
const getStarsDisplay = (level) => {
  const starsCount = level.stars || calculateStars(level);
  return {
    filled: starsCount,
    empty: 3 - starsCount
  };
};

// 判断关卡是否已完成
const isCompleted = (level) => {
  return level.is_completed || (level.answered_questions === level.total_questions && level.total_questions > 0);
};

// 判断是否可以开始新的挑战
const canStartLevel = (level) => {
  return level.answered_questions === 0;
};

// 组件激活时重新加载数据（用于从关卡详情页面返回时更新状态）
onActivated(() => {
  console.log('[LevelList] [DEBUG] 组件激活，重新加载关卡列表')
  loadLevels()
})
</script>

<style scoped>
.level-list {
  padding: 20px;
  width: 100%;
  box-sizing: border-box;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.page-header {
  margin-bottom: 30px;
  padding: 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  box-sizing: border-box;
}

.header-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 2rem;
  margin: 0;
  color: #2c3e50;
  flex: 1;
  text-align: center;
  padding: 0 20px;
  background: linear-gradient(135deg, #42b983 0%, #2a8a64 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.back-btn {
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  white-space: nowrap;
  background-color: #f8f9fa;
  color: #495057;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: #e9ecef;
  transform: scale(1.05);
}

.spacer {
  width: 100px; /* 与返回按钮大致相同的宽度，用于居中标题 */
}

.level-content {
  max-width: 1200px;
  margin: 0 auto;
}

/* 卡片网格布局 */
.level-grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
  justify-items: center;
}

.level-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  padding: 25px;
  box-sizing: border-box;
  transition: all 0.3s;
  width: 100%;
  position: relative;
  overflow: hidden;
  min-height: 280px;
  display: flex;
  flex-direction: column;
}

/* 关卡序号 */
.level-number {
  position: absolute;
  top: 15px;
  right: 15px;
  font-size: 3rem;
  font-weight: bold;
  color: rgba(66, 185, 131, 0.1);
  z-index: 0;
}

.level-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
  cursor: pointer;
}

.level-card h2 {
  color: #2c3e50;
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 1.3rem;
  position: relative;
  z-index: 1;
}

.level-description {
  color: #6c757d;
  margin: 0 0 15px 0;
  line-height: 1.5;
  font-size: 0.9rem;
  flex: 1;
  position: relative;
  z-index: 1;
}

/* 进度条 */
.level-progress {
  margin-bottom: 15px;
  position: relative;
  z-index: 1;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 0.85rem;
  color: #6c757d;
}

.progress-bar {
  width: 100%;
  height: 12px;
  background-color: #e9ecef;
  border-radius: 6px;
  overflow: hidden;
  margin-bottom: 5px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #42b983, #2a8a64);
  border-radius: 6px;
  transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.progress-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 100%);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.progress-text {
  font-weight: 500;
}

.progress-percentage {
  text-align: center;
  font-size: 0.9rem;
  font-weight: bold;
  color: #42b983;
  margin-top: 5px;
}

/* 关卡统计信息 */
.level-stats {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  position: relative;
  z-index: 1;
}

/* 星级显示 */
.level-stars {
  display: flex;
  justify-content: center;
  gap: 5px;
  margin-bottom: 15px;
  position: relative;
  z-index: 1;
}

.star {
  font-size: 1.2rem;
}

.star.filled {
  color: #ffcc00;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.star.empty {
  color: #e0e0e0;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9rem;
  color: #495057;
}

.stat-icon {
  font-size: 1rem;
}

/* 操作按钮 */
.level-actions {
  display: flex;
  gap: 10px;
  margin-top: auto;
  position: relative;
  z-index: 1;
}

.detail-btn, .start-level-btn {
  padding: 10px 20px;
  border-radius: 20px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 0.9rem;
}

.detail-btn {
  background-color: #6c757d;
  color: white;
  flex: 1;
}

.detail-btn:hover {
  background-color: #5a6268;
  transform: scale(1.05);
}

.start-level-btn {
  background-color: #42b983;
  color: white;
  flex: 1;
}

.start-level-btn:hover {
  background-color: #359c6d;
  transform: scale(1.05);
}

/* 已完成徽章 */
.level-badge {
  position: absolute;
  top: 10px;
  left: 10px;
  background-color: #42b983;
  color: white;
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: bold;
  position: relative;
  z-index: 2;
}

.loading, .error, .empty {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  margin-top: 30px;
}

.loading p, .error p, .empty p {
  margin: 0;
  color: #6c757d;
  font-size: 1.1rem;
}

.retry-btn {
  background-color: #ff6b35;
  color: white;
  padding: 12px 25px;
  border-radius: 25px;
  font-weight: bold;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
  margin-top: 20px;
}

.retry-btn:hover {
  background-color: #e55a2b;
  transform: scale(1.05);
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h2 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #6c757d;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #ff6b35;
}

.modal-body {
  padding: 20px;
}

.detail-loading, .detail-error {
  text-align: center;
  padding: 20px;
}

.detail-loading p, .detail-error p {
  margin: 0;
  color: #6c757d;
}

.detail-content p {
  margin: 15px 0;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.detail-content .star {
  font-size: 1.2rem;
}

.detail-content .star.filled {
  color: #ffcc00;
}

.detail-content .star.empty {
  color: #e0e0e0;
}

.detail-content strong {
  color: #2c3e50;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  text-align: center;
}

@media (max-width: 768px) {
  .level-list {
    padding: 15px;
  }
  
  .page-header {
    padding: 15px;
  }
  
  .page-header h1 {
    font-size: 1.5rem;
  }
  
  .level-card {
    padding: 20px;
  }
  
  .level-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .level-actions {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .level-list {
    padding: 10px;
  }
  
  .header-top {
    flex-direction: column;
    gap: 15px;
  }
  
  .page-header h1 {
    font-size: 1.3rem;
    padding: 0;
  }
  
  .back-btn {
    padding: 8px 15px;
    font-size: 0.9rem;
  }
  
  .level-card {
    padding: 15px;
  }
  
  .level-card h2 {
    font-size: 1.3rem;
  }
}
</style>